package com.sojson.util;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import com.sojson.util.cache.CacheUtil;
import com.sojson.util.servlet.ServletUtil;

import cn.hutool.core.util.ObjectUtil;

/**
 * 幂等工具类
 * 
 * @author liu
 * @date 2023-01-09
 */
public class IdempoterUtil {

    /** 等待时间(单位: 秒) */
    public static final int WAIT_TIME = 2;
    /** 请求中的幂等参数 */
    public static final String IDEMPOTENT = "Idempotent";
    /** 请求中的幂等参数值(不校验) */
    public static final String IDEMPOTENT_PERMIT = "permit";
    /** 缓存中的幂等Key */
    public static final String CACHE_IDEMPOTENT_KEY = "Idempotent";
    /** 请求域中的幂等Key */
    public static final String IDEMPOTENT_KEY = "idempotentKey";
    /** 请求域中的幂等Key数据 */
    public static final String IDEMPOTENT_OBJ_KEY = "idempotentObjKey";
    /** 缓存中的幂等值 */
    public static final String CACHE_IDEMPOTENT_VALUE = "Y";
    /** 左括号 */
    public static final String LEFT = "[";
    /** 右括号 */
    public static final String REIGHT = "]";
    /** 是否执行幂等 */
    private static final boolean BREAK_BOOL = false;

    /**
     * 保存响应数据
     * 
     * @param proceed
     * @throws IOException
     */
    public static void save(Object proceed) throws IOException {
        HttpServletRequest request = ServletUtil.getHttpServletRequest();
        Object attribute = request.getAttribute(IDEMPOTENT_OBJ_KEY);
        if (attribute == null) {
            return;
        }

        save(request, proceed);
    }

    /**
     * 保存响应数据
     * 
     * @param request
     * @param proceed
     * @throws IOException
     */
    public static void save(HttpServletRequest request, Object proceed) throws IOException {
        String idempotentObjKey = request.getAttribute(IDEMPOTENT_OBJ_KEY).toString();
        if (!breakBool()) {
            // 缓冲时间
            if (ObjectUtil.isNotNull(proceed)) {
                CacheUtil.setex(idempotentObjKey, proceed, WAIT_TIME);
            } else {
                CacheUtil.setex(idempotentObjKey, "", WAIT_TIME);
            }
        }
    }

    /**
     * 是否执行幂等
     * 
     * @return
     */
    public static boolean breakBool() {
        return BREAK_BOOL;
    }

}
